package com.sc.services;

import com.sc.mapper.NoticeMapper;
import com.sc.pojo.Notice;
import com.sc.utils.DataSourceConfig;
import com.sc.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @description: 公告管理
 * @author: hetao
 * @create: 2023-01-05 22:10
 **/
public class NoticeServices {
    //创建工厂
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DataSourceConfig.class);
    PooledDataSource d = ctx.getBean("dataSource",PooledDataSource.class);
    Connection con;

    {
        try {
            con = d.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 管理员查询所有公告
     * @return
     */
    public List<Notice> selectAllNotice(){
        SqlSession sqlSession = factory.openSession(con);
        NoticeMapper mapper = sqlSession.getMapper(NoticeMapper.class);
        List<Notice> notices = mapper.selectAllNotice();
        sqlSession.close();
        return notices;

    }

    /**
     * 管理员根据公告号删除公告
     * @param noticeid
     */
    public void deleteNoticeById(int noticeid){
        SqlSession sqlSession = factory.openSession(con);
        NoticeMapper mapper = sqlSession.getMapper(NoticeMapper.class);
        mapper.deleteNoticeById(noticeid);
        sqlSession.commit();
        sqlSession.close();

    }

    /**
     * 管理员发布公告
     * @param notice
     */
    public void addNotice(Notice  notice){
        SqlSession sqlSession = factory.openSession(con);
        NoticeMapper mapper = sqlSession.getMapper(NoticeMapper.class);
        mapper.addNotice(notice);
        sqlSession.commit();
        sqlSession.close();
    }

    /**
     * 用户根据当前场地的id查看该场地的所有公告
     * @param fieldid
     * @return
     */
    public List<Notice> selectNoticeById(int fieldid){
        SqlSession sqlSession = factory.openSession(con);
        NoticeMapper mapper = sqlSession.getMapper(NoticeMapper.class);
        List<Notice> notices = mapper.selectNoticeByFieldId(fieldid);
        sqlSession.close();
        return  notices;
    }
}